package com.fordmotor.aspectj;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.function.Function;
@Slf4j
@Component
@Aspect
public class ControllerAdvice {

    @AfterReturning(returning="rvt",pointcut = " execution(public * *..*api.LbsApi.*(..))")
    public Object handle(JoinPoint joinPoint,Object rvt) throws Throwable {
        Object result;
        try {
            Function<JoinPoint, AbstractControllerHandler> build = AbstractControllerHandler.getBuild();
            if (null == build) {
                AbstractControllerHandler.registerBuildFunction(DefaultControllerHandler::new);
            }
            build = AbstractControllerHandler.getBuild();
           // AbstractControllerHandler controllerHandler = new DefaultControllerHandler(proceedingJoinPoint);
            AbstractControllerHandler controllerHandler = build.apply(joinPoint);
            if (null == controllerHandler) {
                log.warn(String.format("The method(%s) do not be handle by controller handler.", joinPoint.getSignature().getName()));
                result = joinPoint.getThis();
            } else {
                result =  controllerHandler.handle(joinPoint,rvt);
            }
        } catch (Throwable throwable) {
            log.error( "Unknown exception- -!",throwable);
            throw throwable;
        }

        return result;
    }
}
